package com.best4cloud.common.core.security;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Optional;

public final class SecurityUtils {

    public static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public static Optional<String> getCurrentUserLogin() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
                .map(authentication -> {
                    if (authentication.getPrincipal() instanceof UserDetails) {
                        UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                        return springSecurityUser.getUsername();
                    }
                    return null;
                });
    }

    /**
     * 加密密码
     * @param password 密码
     * @return
     */
    public static String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }

    /**
     * 对比密码是否一致
     * @param rawPassword 加密前密码
     * @param encodePassword 加密后密码
     * @return
     */
    public static Boolean matchesPassword(String rawPassword, String encodePassword) {
        if (StrUtil.isBlank(rawPassword) || StrUtil.isBlank(encodePassword)) {
            return false;
        }
        return passwordEncoder.matches(rawPassword, encodePassword);
    }
}
